import axios from 'axios'

/**
 * 获取access_token
 * @param corpid        企业ID
 * @param corpsecret    应用的凭证密钥
 * @returns {Promise<any>}
 */
export function getAccessToken(corpid, corpsecret) {
  let url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: {
        corpid,
        corpsecret
      }
    }).then(res => {
      if (res.status === 200) {
        resolve(res.data)
      } else {
        reject(res)
      }
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 发送应用消息
 * @param access_token  调用接口凭证
 * @param params        消息参数，具体参见：https://work.weixin.qq.com/api/doc#10167
 * @returns {Promise<any>}
 */
export function sendMsg(access_token, params) {
  let url = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${access_token}`
  return new Promise((resolve, reject) => {
    axios.post(url, params).then(res => {
      if (res.status === 200) {
        resolve(res.data)
      } else {
        reject(res)
      }
    }).catch(err => {
      reject(err)
    })
  })
}
